package com.hzit.aspect;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.anno.RequiresPermissions;
import com.hzit.entity.LoginUser;
import com.hzit.enums.Logical;
import com.hzit.excep.NotPermissionException;
import com.hzit.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 作者：李嘉浩
 * 时间：2024-08-26-16:07
 * 功能：
 */
@Aspect
@Component
public class PreAuthAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 环绕通知
     * @param point
     * @param permissions
     * @return
     */
    @Around("@annotation(permissions)")
    public Object innerAround(ProceedingJoinPoint point, RequiresPermissions permissions) throws Throwable {
        //得到方法上的权限串列表
        String[] myMethodPermissions = permissions.value();
        //获取权限形式
        Logical logical = permissions.logical();
        //得到当前登录用户的权限列表
        List<String> permissionList=getPerssiinsByToken();
        //判断是否拥有权限
        isExistPermission(myMethodPermissions,permissionList,logical);

        return point.proceed();
    }

    /**
     * 判断是否有权限访问
     * @param myMethodPermissions
     * @param permissionList
     * @param logical
     */
    private void isExistPermission(String[] myMethodPermissions, List<String> permissionList,Logical logical) {
        boolean flag=true;
        for(String permission:myMethodPermissions){
            if (logical==Logical.AND){
                if (!permissionList.contains(permission)){
                    throw new NotPermissionException("权限不足");
                }
                flag=false;
            }
            if (logical==Logical.OR){
                if (permissionList.contains(permission)){
                    flag=false;
                }
            }
            if (flag){
                throw new NotPermissionException("权限不足");
            }
        }
    }

    private List<String> getPerssiinsByToken() {
        //可以在任意位置得到当前的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //得到请求头
        String authorization = request.getHeader("Authorization");
        //得到Token
        String token=getToken(authorization);
        if (StrUtil.isNotBlank(token)){
            Claims claims = JwtUtils.parseToken(token);
            if (claims!=null){
                Object uuid = claims.get("uuid");
                String LoginUserStr = stringRedisTemplate.opsForValue().get("access_token"+uuid);
                LoginUser loginUser = JSON.parseObject(LoginUserStr, LoginUser.class);
                return loginUser.getPermissions();
            }
        }
        return null;

    }

    private String getToken(String authorization) {
        if (authorization!=null){
            return authorization.replace("Bearer ","");

        }
        return null;
    }
}
